package common

import (
	"encoding/json"
	"io/ioutil"
	"net/http"
	"regexp"
	"strings"
)

//将字符串转为map
func Str2Map(jsonData string) (result map[string]interface{}) {
	_ = json.Unmarshal([]byte(jsonData), &result)
	return result
}

//将map转为字符串
func Map2Str(mapData map[string]interface{}) (result string) {
	resultByte, _ := json.Marshal(mapData)
	result = string(resultByte)
	return result
}

func GetPubIp() interface{} {
	res, err := http.Get("https://api.ipify.org/?format=json")
	if err != nil {
		return ""
	}
	defer res.Body.Close()
	content, _ := ioutil.ReadAll(res.Body)
	resMap := Str2Map(string(content))
	return resMap["ip"]
}

func ParseDomain(fullDomain string) (string, string) {
	re := regexp.MustCompile(`[^.]+\.[^.]+$`)
	matched := re.FindAllStringSubmatch(fullDomain, -1)
	domain := matched[0][0]
	subdomain := strings.Replace(fullDomain, "."+domain, "", -1)
	return domain, subdomain
}
